package com.manli.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.manli.api.base.annotation.Permissions;
import com.manli.api.base.beetlsql.BaseDaoManager;
import com.manli.api.base.redis.scenes.RedisScenes;
import com.manli.api.base.redis.scenes.delayjob.Message;
import com.manli.api.base.redis.scenes.delayjob.RedisTaskUtil;
import com.manli.api.base.redis.scenes.delayjob.RedisZSetDelayedQueue;
import com.manli.api.base.redis.scenes.pubsub.MessagePublisher;
import com.manli.api.base.redis.scenes.pubsub.RedisMessageSubscriber;
import com.manli.api.dao.BranchDao;
import com.manli.api.pojo.Result;
import com.manli.api.pojo.UserPermission;
import com.manli.api.service.TestPrimaryService;
import com.manli.api.service.TestSecondService;
import com.manli.api.service.UserPermissionService;
import com.manli.api.util.FileUtil;
import com.manli.api.util.ResultUtil;
import com.manli.common.utils.qiniu.QueryParamsFileKey;
import com.manli.common.utils.qiniu.UploadFilesUtil;
import io.swagger.annotations.ApiOperation;

import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

import javax.servlet.http.HttpServletRequest;


@RestController
//@Api(tags = "测试模块")
public class TestController {
	Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private TestPrimaryService testPrimaryService;
	
	@Autowired
	private TestSecondService testSecondService;
	
	@Autowired
	private UserPermissionService userPermissionService;
	
	@Autowired
	RedisTemplate redisTemplate;
	
	@Autowired
	BranchDao branchDao;
	
	@Autowired
	SQLManager SQLManager;

	@Autowired
	BaseDaoManager manliSQLManager;

	@Autowired
	RedisScenes redisScenes;
	/**
	 * 测试请求返回
	 * @return
	 */
	@ApiOperation(value="测试Api请求", notes="验证请求是否正常")
	@Permissions(module = "", privilege = "", typeOfAccess = Permissions.METHOD_OPEN)
	@RequestMapping(value="/test", method=RequestMethod.POST)
	public Result test() {
		logger.info("进入测试");
		logger.debug("debug");
		logger.trace("trace");
		logger.error("error");
		return ResultUtil.success("HELLO MANLi");
	}


	@Permissions(module = "", privilege = "", typeOfAccess = Permissions.METHOD_OPEN)
	@RequestMapping(value="/insertData", method=RequestMethod.GET)
	public Result insertData(String name) throws Exception{

		String basePath="C:\\Users\\fjc\\Desktop\\" + name;
		String[] list1=new File(basePath).list();
		List<String> strings = Arrays.asList(list1);
		strings.forEach(s1 -> {
			String filePath = basePath + "\\" + s1;
			List<String> list = null;
			try {
				list = FileUtil.readTxtFile(filePath);
			} catch (Exception e) {
				e.printStackTrace();
			}

			for(int i=0;i<list.size() / 3;i++){
				List<String> o3 = list.subList(i*3,i*3 + 3);
				System.out.println(o3);
				SQLReady sqlReady = new SQLReady("insert into yp_province_link (company_name,company_addres,company_phone,level,level_name) values (?,?,?,?,?)",o3.get(0),o3.get(1),o3.get(2),2,s1.replace(".txt",""));
				SQLManager.executeUpdate(sqlReady);
			}
		});




		return ResultUtil.success();
	}
	
	/**
	 * 测试数据库查询 primary
	 * @return
	 */
	@RequestMapping(value="/test2", method=RequestMethod.GET)
	@Permissions(module = "", privilege = "", typeOfAccess = Permissions.METHOD_LOGIN)
	public Result test2(HttpServletRequest request) {
		return ResultUtil.success(userPermissionService.getUserPermission(1,request));
	}
	
	/**
	 * 测试数据库查询 second
	 * @return
	 */
	@RequestMapping(value="/test3", method=RequestMethod.GET)
	@Permissions(module = "", privilege = "", typeOfAccess = Permissions.METHOD_LOGIN)
	public Result test3() {
		return ResultUtil.success(testSecondService.test3());
	}
	/**
	 * 测试事务
	 * 在同一个service中
	 * 同一个地址不同数据库
	 * 不同地址不同数据库
	 * @return
	 */
	@RequestMapping(value="/test4", method=RequestMethod.GET)
	@Permissions(module = "", privilege = "", typeOfAccess = Permissions.METHOD_LOGIN)
	public Result test4() {
		return ResultUtil.success(testPrimaryService.test4());
	}
	/**
	 * 测试事务
	 * 在同一个service中
	 * 同一个地址不同数据库
	 * 不同地址不同数据库
	 * @return
	 */
	@RequestMapping(value="/test5", method=RequestMethod.GET)
	@Permissions(module = "", privilege = "", typeOfAccess = Permissions.METHOD_LOGIN)
	public Result test5() {
		testSecondService.test4();
		testPrimaryService.test4();
		return ResultUtil.success("success");
	}
	/**
	 * 测试单机版redis
	 * @return
	 */
	@RequestMapping(value="/test6", method=RequestMethod.GET)
	@Permissions(module = "", privilege = "", typeOfAccess = Permissions.METHOD_LOGIN)
	public Result test6() {
		redisTemplate.opsForValue().set("测试manli","manli");
		return ResultUtil.success(redisTemplate.opsForValue().get("测试manli"));
	}
	/**
	 * 测试redis session 设置
	 * @return
	 */
	@RequestMapping(value="/test7", method=RequestMethod.GET)
	@Permissions(module = "", privilege = "", typeOfAccess = Permissions.METHOD_LOGIN)
	public Result test7(HttpServletRequest request) {
		request.getSession().setAttribute("manli", "redis-session-manli");
		return ResultUtil.success("SUCCESS");
	}
	/**
	 * 测试redis session 获取
	 * @return
	 */
	@RequestMapping(value="/test8", method=RequestMethod.GET)
	@Permissions(module = "", privilege = "", typeOfAccess = Permissions.METHOD_LOGIN)
	public Result test8(HttpServletRequest request) {
		return ResultUtil.success(request.getSession().getAttribute("manli"));
	}
	
	/**
	 * 测试redis session 获取
	 * @return
	 */
	@RequestMapping(value="/test9", method=RequestMethod.GET)
	@Permissions(module = "", privilege = "", typeOfAccess = Permissions.METHOD_OPEN)
	public Result test9(HttpServletRequest request) {
		String sql =
				"SELECT\n" +
						"\t*\n" +
						"FROM\n" +
						"\t(\n" +
						"\t\tSELECT\n" +
						"\t\t\t*\n" +
						"\t\tFROM\n" +
						"\t\t\t(\n" +
						"\t\t\t\tSELECT DISTINCT\n" +
						"\t\t\t\t\ta.visit_log_id,\n" +
						"\t\t\t\t\ta.openid,\n" +
						"\t\t\t\t\ta.unionid,\n" +
						"\t\t\t\t\ta.goods_def_id,\n" +
						"\t\t\t\t\ta.create_time,\n" +
						"\t\t\t\t\tb.nickname\n" +
						"\t\t\t\tFROM\n" +
						"\t\t\t\t\tvisit_log a\n" +
						"\t\t\t\tLEFT JOIN we_chat_user_info b ON a.unionid = b.unionid\n" +
						"\t\t\t\tWHERE\n" +
						"\t\t\t\t\tdatediff(NOW(), a.create_time) <= 14\n" +
						"\t\t\t\tAND a.goods_def_id = 1\n" +
						"\t\t\t\tORDER BY\n" +
						"\t\t\t\t\ta.create_time DESC\n" +
						"\t\t\t) main\n" +
						"\t\tGROUP BY\n" +
						"\t\t\tmain.unionid\n" +
						"\t) c";

		SQLReady sqlReady = new SQLReady(sql);
		PageQuery<Map> pageQuery = new PageQuery<Map>(1,5);
		PageQuery<Map> query = SQLManager.execute(sqlReady, Map.class,pageQuery);
		System.out.println("数据:" + query.getList());//数据
		System.out.println("数据数量:" + query.getList().size());//数据
		System.out.println("第几页:" + query.getPageNumber());//第几页
		System.out.println("每页几行:" + query.getPageSize());//每页几行
		System.out.println("总页数：" + query.getTotalPage());
		System.out.println("一共有多少条" + query.getTotalRow());
		return ResultUtil.success("success");
	}
	/**
	 * 程序中不允许出现delete 和 drop
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/test10", method=RequestMethod.GET)
	@Permissions(module = "", privilege = "", typeOfAccess = Permissions.METHOD_OPEN)
	public Result test10(HttpServletRequest request) {
		branchDao.deleteById(9999);
		return ResultUtil.success("success");
	}
	/**
	 * 测试sql注入
	 */
	@RequestMapping(value="/test11", method=RequestMethod.GET)
	@Permissions(module = "", privilege = "", typeOfAccess = Permissions.METHOD_OPEN)
	public Result test11(HttpServletRequest request) {
		String sql = "select * from user where user_id = ?  ";
		SQLReady sqlReady = new SQLReady(sql,"1 or 1=1");
		PageQuery<UserPermission> pageQuery = new PageQuery<UserPermission>(1,20);
		PageQuery<UserPermission> query = SQLManager.execute(sqlReady,UserPermission.class,pageQuery);
		return ResultUtil.success(query.getList());
	}

	/**
	 * 测试七牛删除文件
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/test12", method=RequestMethod.GET)
	@Permissions(module = "", privilege = "", typeOfAccess = Permissions.METHOD_OPEN)
	public Result test12(HttpServletRequest request) throws Exception {
		QueryParamsFileKey queryParamsFileKey = new QueryParamsFileKey();
		queryParamsFileKey.setFileKey("/ssg/2.jpg");
		UploadFilesUtil.deleteFile(queryParamsFileKey);

		return ResultUtil.success("success");
	}


	@Autowired
	@Qualifier("redisPublisherForTopic1")
	private MessagePublisher redisPublisher1;

	@Autowired
	@Qualifier("redisPublisherForTopic2")
	private MessagePublisher redisPublisher2;

	@Autowired
	@Qualifier("messageListener1")
	private RedisMessageSubscriber subscriber1;

	@Autowired
	@Qualifier("messageListener2")
	private RedisMessageSubscriber subscriber2;


	/**
	 * redis scens测试
	 */
	@RequestMapping(value="/test13", method=RequestMethod.GET)
	@Permissions(module = "", privilege = "", typeOfAccess = Permissions.METHOD_OPEN)
	public Result test13(HttpServletRequest request) throws Exception {
		/**
		 * IP限制访问
		 */
		boolean res = redisScenes.calculateIpCount("127.0.0.1",10,10);
		/**
		 * 一条消息一次消费
		 */
		JSONObject object = new JSONObject();
		object.put("test","test");
		redisScenes.pubOneOffMsg("task-a", object);
		System.out.println(redisScenes.subOneOffMsg("task-a"));
		System.out.println(redisScenes.subOneOffMsg("task-a"));

		/**
		 * 测试订阅发布
		 */
		// 循环发布10次消息, 主要方法 redisTemplate.convertAndSend
		for (int i = 0; i < 10; i++) {
			String message = "Topic1 Message : " + i;
			redisPublisher1.publish(message);
		}

		// 循环发布10次消息, 主要方法 redisTemplate.convertAndSend
		for (int i = 0; i < 10; i++) {
			String message = "Topic2 Message : " + i;
			redisPublisher2.publish(message);
		}

		// 获取存储的订阅消息
		List<String> messageList1 = subscriber1.getMessageList();
		for (int i = 0; i < messageList1.size(); i++) {
			logger.info(messageList1.get(i));
		}

		// 获取存储的订阅消息
		List<String> messageList2 = subscriber2.getMessageList();
		for (int i = 0; i < messageList2.size(); i++) {
			logger.info(messageList2.get(i));
		}


		return ResultUtil.success("success");
	}

	/**
	 * 测试redis延迟消息
	 */
	@Autowired
	RedisTaskUtil redisTaskUtil;

	@GetMapping("/redis/zSetDelayedQueue")
	@Permissions(module = "", privilege = "", typeOfAccess = Permissions.METHOD_OPEN)
	public Result zSetDelayedQueue() {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("a",1);
		Message message1 = new Message(jsonObject.toJSONString(), 1000 * 5L);
		//Message message2 = new Message("world", 1000 * 7L);

		String queueName = "zset_queue";

		BlockingQueue<Message> delayedQueue = new DelayQueue<>();

		RedisZSetDelayedQueue redisZSetDelayedQueue = new RedisZSetDelayedQueue(redisTemplate, queueName, delayedQueue);

		redisZSetDelayedQueue.offerMessage(message1);
		//redisZSetDelayedQueue.offerMessage(message2);
		redisTaskUtil.asyncZSetTask(queueName);

		return ResultUtil.success("success");

	}




}
